package com.imooc.reader.management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imooc.reader.management.entity.Book;
import com.imooc.reader.management.mapper.BookMapper;
import com.imooc.reader.management.mapper.EvaluationMapper;
import com.imooc.reader.management.mapper.MemberReadStateMapper;
import com.imooc.reader.management.service.BookService;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Service
public class BookServiceImpl implements BookService {
    @Resource
    private BookMapper bookMapper;
    @Resource
    private EvaluationMapper evaluationMapper;
    @Resource
    private MemberReadStateMapper memberReadStateMapper;
    @Override
    public IPage<Map> selectBookMap(Integer page, Integer rows) {
        return bookMapper.selectBookMap(new Page(page,rows));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Book createBook(Book book) {
        bookMapper.insert(book);
        return book;
    }
    @CacheEvict(value = "book" , key = "#book.bookId") //book:32
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Book updateBook(Book book) {
        Book b = bookMapper.selectById(book.getBookId());
        b.setBookName(book.getBookName());
        b.setSubTitle(book.getSubTitle());
        b.setAuthor(book.getAuthor());
        b.setCategoryId(book.getCategoryId());
        b.setDescription(book.getDescription());
        b.setCover(book.getCover());
        bookMapper.updateById(book);
        return book;
    }
    @CacheEvict(value = "book" , key = "#bookId")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Book deleteBook(Long bookId) {
        Book book = bookMapper.selectById(bookId);
        bookMapper.deleteById(bookId);
        QueryWrapper wrapper1 = new QueryWrapper();
        wrapper1.eq("book_id", bookId);
        evaluationMapper.delete(wrapper1);
        QueryWrapper wrapper2 = new QueryWrapper();
        wrapper2.eq("book_id", bookId);
        memberReadStateMapper.delete(wrapper2);
        return book;
    }
    @CacheEvict(value = "book" , allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateScore() {
        bookMapper.updateScore();
    }
}
